package com.by_man.presenter.module_health_consultant;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.by_man.presenter.wechat_related.Constants;
import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.main_page.MainActivity;
import com.by_man.presenter.wechat_related.GetFromWXActivity;
import com.by_man.presenter.wechat_related.ShowFromWXActivity;
import com.by_man.repository.LocalDataManager;
import com.by_man.repository.UserInfos;
import com.tencent.mm.sdk.openapi.BaseReq;
import com.tencent.mm.sdk.openapi.BaseResp;
import com.tencent.mm.sdk.openapi.ConstantsAPI;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.ShowMessageFromWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXAppExtendObject;
import com.tencent.mm.sdk.openapi.WXMediaMessage;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * 显示医生详细信息
 * Created by man on 2017-02-23.
 */
public class DoctorInfosActivity extends AppCompatActivity implements IWXAPIEventHandler {
    private RequestQueue rQueue;
    private ImageLoader imageLoader;
    private Views views;

    private Handler handler;

    private final static int CHOSE_DOCTOR_SUCCESS = 0x1;
    private final static int CHOSE_DOCTOR_FAIL = 0x2;
    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doctor_infos);
        rQueue = SharedApplication.getrQueue(getApplication());
        rQueue.start();
        imageLoader = SharedApplication.getImageLoader(getApplication());
        views = new Views();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case CHOSE_DOCTOR_SUCCESS:
                        choseDoctorSuccess();
                        break;
                    case CHOSE_DOCTOR_FAIL:
                        choseDoctorFail();
                        break;
                    default:
                        break;
                }
            }
        };
        initView();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

    private class Views {
        TextView nameText;
        TextView phoneText;
        TextView jobText;
        TextView sexText;
        TextView introduction;
        TextView numText;
        ImageView img;
        Button btn;
    }

    private void initView() {
        // 初始化ToolBar
        Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        // 将所有ui组件汇集
        views.nameText=(TextView)findViewById(R.id.doc_name);
        views.phoneText = (TextView) findViewById(R.id.doc_phone);
        views.jobText = (TextView) findViewById(R.id.doc_job);
        views.sexText = (TextView) findViewById(R.id.doc_sex);
        views.introduction = (TextView) findViewById(R.id.introduction);
        views.numText=(TextView) findViewById(R.id.doc_num);
        views.img = (ImageView) findViewById(R.id.image_view);
        views.btn = (Button) findViewById(R.id.choose);

        // 设置
        views.nameText.setText(getIntent().getStringExtra("name"));
        try {
            JSONArray jsonArray = new JSONArray(getIntent().getStringExtra("jsonString"));
            JSONObject temp;
            // 应该不用for循环，只有一项
            for(int j=0;j<jsonArray.length();j++) {
                temp = (JSONObject) jsonArray.get(j);
//                HashMap<String, Object> map = new HashMap<String, Object>();
                final String list_id = temp.getString("list_id");
                int i = Integer.valueOf(list_id).intValue();   //强制类型转换
                //联系方式
                if (i == 6) {
                    String phone = temp.getString("value");
                    views.phoneText.setText(phone);
                }
                //工作职称
                if (i == 14) {
                    String job = temp.getString("value");
                    views.jobText.setText(job);
                }
                //工作单位
                if (i == 15) {
                    String work = temp.getString("value");
                    views.sexText.setText(work);
                }
                //自我简介
                if (i == 19) {
                    String introInfo = temp.getString("value");
                    views.introduction.setText(introInfo);
                }
                if(i==33) {
                    int num = Integer.parseInt(temp.getString("value"));
                    if (num!= 0) {
                        views.numText.setText(String.valueOf(num));
                        // numText.setText(num);
                        if (num == 10) {
                            // 逻辑有误，后面讲改变设置
                            views.btn.setText("该顾问人数已满，谢谢信任");
                            views.btn.setBackgroundColor(0xff6db88a);
                            views.btn.setClickable(false);
                        }
                    } else {
                        views.numText.setText("0");
                    }
                }
                if (i==18){
                    String pic_path = temp.getString("value");
                    if(pic_path.length()!=0)
                    {
                        ImageLoader.ImageListener listener = ImageLoader.getImageListener(views.img,R.drawable.no, R.drawable.no);
                        imageLoader.get(pic_path,listener);
                    }
                }
            }
        } catch (JSONException je) {
            je.printStackTrace();
        }

        // 分不同情况设定button的监听
        if (getIntent().getBooleanExtra("ischosed", false)) {
            views.btn.setText("聊天");
            views.btn.setBackgroundColor(0xff6db88a);

            // 通过WXAPIFactory工厂，获取IWXAPI的实例
            api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
            // 进行启动微信的处理
            views.btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(DoctorInfosActivity.this, "即将启动微信，请稍后" + api.openWXApp(), Toast.LENGTH_LONG).show();
                }
            });

            api.handleIntent(getIntent(), this);
        } else {
            views.btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    choseDoctorByNet();
                }
            });
        }
    }

    // 进行网络请求
    private void choseDoctorByNet() {
        String url = getResources().getString(R.string.chose_consultant);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("token", UserInfos.token);
        params.put("arg", getIntent().getStringExtra("name"));
        // 将请求参数封装到json对象中
        JSONObject jsonObject = new JSONObject(params);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            if (jsonObject.getBoolean("isFull")) {
                                Message msg = handler.obtainMessage();
                                msg.what = CHOSE_DOCTOR_SUCCESS;
                                msg.sendToTarget();
                            }
                        } catch (JSONException je) {
                            je.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("DoctorInfosError", volleyError.getMessage(),volleyError);
                        Message msg = handler.obtainMessage();
                        msg.what = CHOSE_DOCTOR_FAIL;
                        msg.sendToTarget();
                    }
                });
        rQueue.add(jsonObjectRequest);
    }

    private void choseDoctorSuccess() {
        views.btn.setText("已选择");
        views.btn.setBackgroundColor(0xff6db88a);
    }

    private void choseDoctorFail() {
        AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle("提醒")
                .setMessage("选择医生失败，是否继续请求？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        choseDoctorByNet();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).create();
        alertDialog.show();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {
        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                goToGetMsg();
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                goToShowMsg((ShowMessageFromWX.Req) req);
                break;
            default:
                break;
        }
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        int result = 0;

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                result = R.string.errcode_success;
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = R.string.errcode_cancel;
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = R.string.errcode_deny;
                break;
            default:
                result = R.string.errcode_unknown;
                break;
        }

        Toast.makeText(this, result, Toast.LENGTH_LONG).show();
    }

    private void goToGetMsg() {
        Intent intent = new Intent(this, GetFromWXActivity.class);
        intent.putExtras(getIntent());
        startActivity(intent);
        finish();
    }

    private void goToShowMsg(ShowMessageFromWX.Req showReq) {
        WXMediaMessage wxMsg = showReq.message;
        WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;
        StringBuffer msg = new StringBuffer(); // 组织一个待显示的消息内容
        msg.append("description: ");
        msg.append(wxMsg.description);
        msg.append("\n");
        msg.append("extInfo: ");
        msg.append(obj.extInfo);
        msg.append("\n");
        msg.append("filePath: ");
        msg.append(obj.filePath);
        Intent intent = new Intent(this, ShowFromWXActivity.class);
        intent.putExtra(Constants.ShowMsgActivity.STitle, wxMsg.title);
        intent.putExtra(Constants.ShowMsgActivity.SMessage, msg.toString());
        intent.putExtra(Constants.ShowMsgActivity.BAThumbData, wxMsg.thumbData);
        startActivity(intent);
        finish();
    }
}
